#!/usr/bin/env python3
# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import logging
import os
import json
from tqdm import tqdm
import pandas as pd
import multiprocessing
import time
import torch
import glob
import math
from data_unpack_demo_index_path import DataUnPack
from sys import argv
import numpy as np
import soundfile as sf
import io

desc_data_unpack = DataUnPack()


def convert_to_bytes(x):
    if isinstance(x, float):
        return str(x).encode()  # 将float转为字符串再编码为bytes
    return x


# def job(utt_list, parquet_file, utt2parquet_file, audio_user_path,audio_user_text, audio_user_lang,audio_assistant_path,audio_assistant_text,audio_assistant_lang):
def job(utt_list, parquet_file, utt2parquet_file):
    try:
        start_time = time.time()
        user_data_list = []
        user_text_list = []
        assist_text_list = []
        assist_data_list = []
        audio_user_lang_list = []
        audio_assistant_lang_list = []
        for utt in tqdm(utt_list):
            # data = open(audio_user_path[utt], 'rb').read()
            _, data = desc_data_unpack.read_buffer_from_seq(audio_user_path[utt])
            buffer = io.BytesIO()
            sf.write(buffer, data, 16000, 'PCM_16', format='WAV')
            wav_data = buffer.getvalue()
            buffer.close()
            user_data_list.append(wav_data)
            user_text_list.append(audio_user_text[utt])
            audio_user_lang_list.append(audio_user_lang[utt])

            # data = open(audio_assistant_path[utt], 'rb').read()
            # assist_data_list.append(data)
            assist_text_list.append(audio_assistant_text[utt])
            audio_assistant_lang_list.append(audio_assistant_lang[utt])

        user_wav_list = [audio_user_path[utt] for utt in utt_list]
        # assist_wav_list = [audio_assistant_path[utt] for utt in utt_list]
        # 保存到parquet,utt2parquet_file,spk2parquet_file
        df = pd.DataFrame()
        df['utt'] = utt_list
        df['user_text'] = user_text_list
        df['user_wav'] = user_wav_list
        df['user_audio_data'] = user_data_list
        df['user_audio_data_lang'] = audio_user_lang_list

        df['assist_text'] = assist_text_list
        # df['assist_wav'] = assist_wav_list
        # df['assist_audio_data'] = assist_data_list
        df['assist_audio_data_lang'] = audio_assistant_lang_list

        df.to_parquet(parquet_file)
        with open(utt2parquet_file, 'w') as f:
            json.dump({k: parquet_file for k in utt_list}, f, ensure_ascii=False, indent=2)
        logging.info('spend time {}'.format(time.time() - start_time))
    except Exception as e:
        print('error')
        print(e)


if __name__ == "__main__":
    data = open("./speech-to-text.list" + argv[1], "r")
    lines = data.readlines()
    audio_user_path = {}
    audio_user_text = {}
    audio_user_lang = {}
    audio_assistant_path = {}
    audio_assistant_text = {}
    audio_assistant_lang = {}
    for line in lines:
        path = line.strip()
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        for item in data:
            id_ = item.get('id')
            conv = item.get('conversations')
            for i in range(2):
                item_conv = conv[i]
                if item_conv.get('from') == 'user':
                    audio_user_path[id_] = item_conv['audio']
                    audio_user_text[id_] = item_conv['ground_truth']
                    audio_user_lang[id_] = item_conv['source_lang']
                if item_conv.get('from') == 'assistant':
                    # audio_assistant_path[id_] = item_conv['audio']
                    audio_assistant_text[id_] = item_conv['value']
                    audio_assistant_lang[id_] = item_conv["target_lang"]

    # Using process pool to speedup
    num_processes = 16
    num_utts_per_parquet = 10000
    des_dir = "/apdcephfs_zwfy/share_303841515/Tealab/data/translation/speech-to-text/" + argv[1]
    pool = multiprocessing.Pool(processes=num_processes)
    parquet_list, utt2parquet_list = [], []
    utts = list(audio_user_path.keys())
    print("uttslen:", len(utts))
    for i, j in enumerate(range(0, len(utts), num_utts_per_parquet)):
        parquet_file = os.path.join(des_dir, 'parquet_{:09d}.tar'.format(i))
        utt2parquet_file = os.path.join(des_dir, 'utt2parquet_{:09d}.json'.format(i))
        parquet_list.append(parquet_file)
        utt2parquet_list.append(utt2parquet_file)
        pool.apply_async(job, (utts[j: j + num_utts_per_parquet], parquet_file, utt2parquet_file))
        # job(utts[j: j + num_utts_per_parquet], parquet_file, utt2parquet_file)
        # pool.apply_async(job, (utts[j: j + num_utts_per_parquet], parquet_file, utt2parquet_file ))
    pool.close()
    pool.join()

    with open('{}/data.list'.format(des_dir), 'w', encoding='utf8') as f1, \
            open('{}/utt2data.list'.format(des_dir), 'w', encoding='utf8') as f2:
        for name in parquet_list:
            f1.write(name + '\n')
        for name in utt2parquet_list:
            f2.write(name + '\n')